import logging
from logging.handlers import RotatingFileHandler
import os
from auth.models import db
from auth.models import User
from flask_login import current_user,LoginManager

def auth_init(app):
    # 初始化数据库
    db.init_app(app)
    with app.app_context():
        db.create_all()

    # 配置日志
    if not os.path.exists('logs'):
        os.mkdir('logs')
    file_handler = RotatingFileHandler(
        app.config['LOG_FILE'], 
        maxBytes=1024*1024, 
        backupCount=10
    )
    file_handler.setFormatter(logging.Formatter(
        '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'
    ))
    file_handler.setLevel(app.config['LOG_LEVEL'])
    app.logger.addHandler(file_handler)
    app.logger.setLevel(app.config['LOG_LEVEL'])

    # 安全日志配置
    security_logger = logging.getLogger('security')
    security_logger.setLevel(logging.WARNING)
    security_handler = RotatingFileHandler('logs/security.log', maxBytes=1e6, backupCount=5)
    security_handler.setFormatter(logging.Formatter('%(asctime)s - %(message)s'))
    security_logger.addHandler(security_handler)


    # 创建 LoginManager 实例
    login_manager = LoginManager()
    login_manager.init_app(app)  # 先初始化并绑定到app
    login_manager.login_view = 'auth.login'  # 设置登录页面
    # 用户加载回调 - 必须定义在应用工厂函数内
    @login_manager.user_loader
    def load_user(user_id):
        """加载用户的回调函数，必须返回 User 对象或 None"""
        try:
            # 使用当前应用的上下文
            with app.app_context():
                # 将 user_id 转换为整数
                user = User.query.get(int(user_id))
                if user:
                    app.logger.debug(f"Loaded user: {user.username} (ID: {user_id})")
                else:
                    app.logger.warning(f"User not found for ID: {user_id}")
                return user
        except Exception as e:
            app.logger.error(f"Error loading user {user_id}: {str(e)}")
            return None
        
    # 将current_user注入所有模板
    @app.context_processor
    def inject_user():
        return dict(current_user=current_user)